package com.orm.mybatis.token.redis.interceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.orm.mybatis.token.redis.annotation.PassToken;
import com.orm.mybatis.token.redis.utils.RedisUtils;
import com.orm.mybatis.token.redis.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * 添加拦截器
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        //如果不是映射到方法直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        if(method.isAnnotationPresent(PassToken.class)|| handlerMethod.getBeanType().getAnnotation(PassToken.class) != null) { //方法上面是否有注解？
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.value()){
                return true;
            }
        }
        HashMap<String,String> hashMap = new HashMap<>();
        String token = request.getHeader("token");
        try {
             String redisToken = (String)redisUtils.get(token);
            if(StringUtils.hasText(redisToken)){
                Integer time = Math.toIntExact(redisUtils.getExpire(token));
                if (time>0&&time<10){
                    System.out.println("续期redis");
                    redisUtils.expire(redisToken,20);
                }
                return true;
            }

            TokenUtil.verifyToken(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            hashMap.put("msg","签名不一致");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            hashMap.put("msg","令牌过期异常");
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            hashMap.put("msg", "算法不匹配异常");
        }catch (InvalidClaimException e){
            e.printStackTrace();
            hashMap.put("msg","失效的claim异常");
        }catch (Exception e){
            e.printStackTrace();
            hashMap.put("msg","token无效");
        }
        String resultJson = JSON.toJSONString(hashMap);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(resultJson);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
